<template>
  <div class="cart">
    <div class="width_1200 logo">
      <div class="toolItem">
        <svg class="icon-third" aria-hidden="true" style="font-size: 8px">
          <use xlink:href="#icon-third-gouwuche"></use>
        </svg>
        <span class="toolTitle">购物车(<span>{{ totalGoodsNumber }}</span>)</span>
      </div>
    </div>
    <a-divider />
    <!-- 购物车主体 -->
    <div class="cart-content width_1200 center">
      <div class="available-area">
        <a-steps
          :current="0"
          :items="[
            {
              title: '我的购物车',
            },
            {
              title: '填写订单信息',
            },
            {
              title: '成功提交订单',
            },
          ]"
        ></a-steps>
      </div>
      <!-- 购物车商品列表 -->
      <div class="cart-goods">
        <div class="cart-goods-title">
          <div class="width_60">
            <a-checkbox
              v-model:checked="allChecked"
              @change="changeChecked(allChecked, 'all','')"
            >全选
            </a-checkbox>
          </div>
          <div class="goods-title">商品</div>
          <div class="width_150">单价（元）</div>
          <div class="width_150">小计</div>
          <div class="width_100">操作</div>
        </div>
        <div v-if="cartList.length === 0" class="cart-empty">
          <p>
            <a-empty :image="simpleImage" description="购物车空空如也" />
          </p>
          <router-link to="/mall">去选购&gt;</router-link>
        </div>
        <div
          v-else
          class="cart-goods-items"
          v-for="(shop, index) in cartList"
          :key="index"
        >
          <template v-for="(goods, goodsIndex) in shop?.skuList" v-if="shop?.skuList?.length > 0" :key="goodsIndex">
            <div class="goods-item">
              <div class="width_60">
                <a-checkbox
                  v-model:checked="goods.checked"
                  @change="changeChecked(goods.checked, 'goods', goods.goodsId)"
                ></a-checkbox>
              </div>
              <div
                class="goods-title"
                @click="goGoodsDetail(goods.goodsId)">
                <img :src="getFileAccessHttpUrl(goods.goodsImage)" />
                <div>
                  <p style="font-size: 14px">
                    {{ goods.goodsName }}
                  </p>
                </div>
              </div>
              <div class="width_150">
                {{ unitPrice(goods.purchasePrice, "￥", "") }}
              </div>
              <div class="width_150">
                {{ unitPrice(goods.subTotal, "￥", "") }}
              </div>
              <div class="width_100">
                <a-space>
                  <a-button
                    size="small"
                    type="primary"
                    danger
                    @click="delGoods(goods.goodsId)"
                  >删除
                  </a-button>
                </a-space>
              </div>
            </div>
          </template>
        </div>
        <!-- 底部支付栏 -->
        <div class="cart-goods-footer">
          <div>
            <div class="width_60">
              <a-checkbox
                v-model:checked="allChecked"
                @change="changeChecked(allChecked, 'all','')"
              >全选
              </a-checkbox>
            </div>
            <div class="width_100 handle-btn" @click="delCheckedGoods()">
              删除选中商品
            </div>
            <div class="width_100 handle-btn" @click="clearCart">
              清空购物车
            </div>
          </div>
          <div>
            <div class="selected-count">
              已选择<span style="margin: 0 3px;font-weight: 700">{{ checkedGoodsNumber }}</span
            >件商品
            </div>
            <div class="ml_20 total-price">
              总价:
              <div>{{ unitPrice(checkTotalPrice, "￥", "") }}</div>
            </div>
            <div class="pay ml_20" @click="pay">去结算</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { unitPrice } from "@/utils";
import { onMounted, ref } from "vue";
import {
  allGoodsChecked,
  batchDelCartGoods,
  clearCartGoods,
  delCartGoods,
  getCart,
  sellerChecked,
  skuChecked
} from "@/api/cart";
import { getFileAccessHttpUrl } from "@/utils/compUtils";
import { useMessage } from "@/hooks/web/useMessage";
import { Empty } from "ant-design-vue";
import { useRouter } from "vue-router";

const router = useRouter();

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const { createConfirm } = useMessage();
const { createMessage } = useMessage();

const loading = ref<boolean>(false);
const checkedGoodsNumber = ref<any>(0); // 选中商品数量
const checkTotalPrice = ref<any>(0);
const totalGoodsNumber = ref<any>(0);
const allChecked = ref<boolean>(false); // 全选
const cartList = ref<any>([]); // 购物车列表

// 跳转商品详情
function goGoodsDetail(goodsId) {
  let routeUrl = router.resolve({
    path: `/mall/goods/detail/${goodsId}`
  });
  window.open(routeUrl.href, "_blank");
}


// 删除商品
function delGoods(id) {
  createConfirm({
    iconType: "warning",
    title: "删除",
    content: "确定要删除该商品吗？",
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await delCartGoods(id);
      createMessage.success("删除成功");
      await getCartList();
    }
  });
}

// 删除选中的商品
function delCheckedGoods() {
  const idArr = [];
  cartList.value.forEach((shop) => {
    shop.skuList.forEach((goods) => {
      if (goods.checked) {
        idArr.push(goods.goodsId);
      }
    });
  });
  if (idArr?.length == 0) {
    createMessage.warning("请先选择商品");
    return;
  }
  createConfirm({
    iconType: "warning",
    title: "删除",
    content: "确定要删除选中的商品吗？",
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await batchDelCartGoods(idArr.join(","));
      createMessage.success("删除成功");
      await getCartList();
    }
  });
}

// 清空购物车
function clearCart() {
  createConfirm({
    iconType: "warning",
    title: "提示",
    content: "确定要清空购物车吗？清空后不可恢复",
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      await clearCartGoods();
      createMessage.success("清空购物车成功");
      await getCartList();
    }
  });
}

// 跳转支付页面
function pay() {
  if (checkedGoodsNumber.value > 0) {
    router.push({ path: "/mall/pay", query: { way: 1 } });
  } else {
    createMessage.warning("请至少选择一件商品");
  }
}

// 设置商品选中状态
async function changeChecked(checked, type, id) {
  if (type === "all") {
    // 全选
    await allGoodsChecked(checked);
  } else if (type === "shop") {
    // 选中店铺所有商品
    await sellerChecked({ checked: checked, sellerId: id });
  } else {
    // 单个商品
    await skuChecked({ checked: checked, goodsId: id });
  }
  await getCartList();
}

// 购物车列表
async function getCartList() {
  loading.value = true;
  try {
    const data: any = await getCart();
    cartList.value = data.result.cartList;
    checkedGoodsNumber.value = data.result.checkedGoodsNumber;
    checkTotalPrice.value = data.result.checkTotalPrice;
    totalGoodsNumber.value = data.result.totalGoodsNumber;
    allChecked.value = data.result.allChecked;
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  getCartList();
});

</script>

<style scoped lang="scss">
@import "@/assets/style/course/global.scss";

.cart {
  min-height: 89vh;
}

.footer {
  margin-top: 10px;
}

/** logo 搜索 start **/
.logo {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px auto 0;
}

.cart-content {
  margin: 0 auto;
  width: 1200px;
  position: relative;
}

/** 步骤条和配送区域总体 */
.available-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

/** 商品列表 */
.cart-goods {
  &-title {
    height: 50px;
    @include background_color($light_white_background_color);
    @include title_color($title_color);
    display: flex;
    align-items: center;
    padding: 0 20px;

    div {
      text-align: center;
    }

    .goods-title {
      flex: 1;
    }
  }

  .cart-empty {
    width: 100%;
    text-align: center;
    height: 300px;
    padding-top: 100px;
  }

  &-items {
    .shop-name {
      height: 50px;
      display: flex;
      align-items: center;
      padding: 0 20px;
      position: relative;
      @include title_color($light_title_color);

      > * {
        width: 50%;
      }

      .go-shop-page {
        margin-left: 10px;
      }

      .go-shop-page:hover {
        color: $theme_color;
        cursor: pointer;
      }

      .customer-service {
        margin-left: 5px;
        color: #fcc217;
        cursor: pointer;

        &:hover {
          color: $theme_color;
        }
      }
    }

    .goods-item {
      position: relative;
      @extend .cart-goods-title;
      @include background_color($light_white_background_color);
      padding: 10px 20px;
      height: auto;

      > div:nth-child(1) {
        padding-left: 15px;
        width: 30px;
      }

      > div:nth-child(2) {
        cursor: pointer;
        display: flex;
        box-sizing: border-box;
        padding-left: 20px;
        position: relative;

        img {
          width: 70px;
          height: 70px;
        }

        > div > p {
          @include content_color($light_content_color);
          font-size: 13px;
          text-align: left;
          margin-left: 10px;

          &:hover {
            color: $theme_color;
          }
        }
      }

      > div:nth-child(5) {
        font-weight: bold;
      }

      .num-input {
        width: 60px;
        border: 1px solid #999;
        border-radius: 5px;
        padding: 0 5px;

        &:focus {
          outline-color: $theme_color;
        }
      }
    }
  }

  &-footer {
    @extend .cart-goods-title;
    position: sticky;
    bottom: 0;
    border-top: 1px solid #ddd;
    margin-top: 10px;
    padding: 0 0 0 20px;
    line-height: 50px;
    justify-content: space-between;

    > div {
      display: flex;
    }

    .selected-count {
      span {
        color: $theme_color;
      }
    }

    .save-price span {
      color: #000;
    }

    .total-price div {
      color: $theme_color;
      font-size: 20px;
    }

    .pay {
      background-color: $theme_color;
      width: 150px;
      font-size: 20px;
      color: #fff;
      height: 100%;
      line-height: 50px;
      cursor: pointer;
    }
  }

  .handle-btn {
    font-size: 12px;
    color: $handle-btn-color;
    cursor: pointer;

    &:hover {
      color: $theme_color;
    }
  }
}

.width_150 {
  width: 150px;
}

.width_60 {
  width: 60px;
}

.cart-goods-footer > div {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.total-price {
  display: flex;
  align-items: center;
}


.toolItem {
  display: flex;
  align-items: center;
}

.toolTitle {
  font-size: 20px;
  margin-left: 10px
}

:deep(.ant-input-number .ant-input-number-input) {
  color: #8c8c8c;
}

:deep( .ant-btn.ant-btn-sm) {
  font-size: 12px;
}

</style>
